<template>
  <div class="search_page">
    <!-- 顶部导航栏 -->
    <Navbar title="搜索" placeholder>
      <template #left>
        <RouterLink :to="{ name: 'home' }">
          <Icon name="zuojiantou" color="#fff" size="20" />
        </RouterLink>
      </template>
    </Navbar>
    <div class="comment_list_wrap_search">
      <div class="input_wrap">
        <div class="lf">
          <Icon name="search1" color="#a6a5a4" size="21"></Icon>
        </div>
        <input :placeholder="Inputplaceholder" class="input" ref="InputRef" v-model="InputVal" @input="handleInput">
        <div class="rt" v-if="isShow" @click="clearInput">
          <Icon name="close" color="#a6a5a4" size="12"></Icon>
        </div>
      </div>
    </div>
    <Tab @change="handleTabChange">
      <TabItem title="视频">
        <div class="search_user_video_list">
          <div class="item" v-for="item in VideoList" :key="item.videoId" @click="handleVideoClick(item.videoId)">
            <div class="avatar">
              <img :src="item.videoCover" alt="" />
            </div>
            <div class="item_bottom_info">
              <div class="item_bottom_info_desc">{{ item.videoDesc }}</div>
              <div class="item_bottom_info_user">
                <div class="item_bottom_info_user_userimg">
                  <img :src="item.userAvatar" alt="">
                  <span class="item_bottom_info_user_userimg_name">{{ item.userNickname }}</span>
                </div>
                <div class="item_bottom_info_user_lick">
                  <div class="item_bottom_info_user_lick_item">
                    <Icon name="xin-2" size="14" color="#fff"></Icon>
                    <span class="item_bottom_info_user_lick_num">{{ item.likeNum }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </TabItem>
      <TabItem title="用户">
        <div class="fan_list">
          <div class="fan_item" v-for="item in UserList" :key="item.userId" @click="handleFriendClick(item.userId)">
            <div class="avatar">
              <img :src="item.userAvatar" alt="">
            </div>
            <div class="info">
              <div class="name">
                {{ item.userNickname }}
              </div>
              <div class="desc">
                {{ item.userDesc }}
              </div>
            </div>
            <!-- myRelation == fan 也是 关注状态 -->
            <div class="follow" :class="{ 'active': item.myRelation === 'follow' || item.myRelation === 'both' }"
              @click="handleFollow(item.userId)">
              {{ item.myRelation == 'follow' ? '已关注' : item.myRelation == 'none' ? '关注' : item.myRelation == 'fan' ?
                '关注' :
                '相互关注' }}
            </div>
          </div>
        </div>
      </TabItem>
    </Tab>
    <!-- 视频播放页 -->
    <transition name="fade-left">
      <VerticalFeed v-if="showVerticalFeed" v-model="showVerticalFeed" :currentIndex="currentVideoIndex"
        :feedData="VideoList" />
    </transition>

  </div>
</template>
<script setup>
import { ref, computed, defineAsyncComponent } from 'vue'
import Navbar from '@/components/common/Navbar.vue';
import Icon from '@/components/common/Icon.vue'
import Tab from '@/components/common/Tab.vue'
import TabItem from '@/components/common/TabItem.vue'
import { useUserStore } from '@/stores/userinfo'
const userInfo = useUserStore()
const user = computed(() => userInfo.userInfo)
const userId = computed(() => user.value?.userId)
const InputRef = ref(null)

// 输入框placeholder
import { searchVideoAPI, searchUserAPI, followUserAPI } from '@/api/search'
const currentIndex = ref(0)
const VideoList = ref([])// 视频列表
const UserList = ref([])// 用户列表
const Inputplaceholder = computed(() => {
  return currentIndex.value === 0
    ? '输入关键词进行搜索(视频)'
    : '输入关键词进行搜索(用户昵称)'
})
const InputVal = ref('')
const handleInput = async () => {
  if (InputVal.value.trim() === '') {
    return
  }
  // 视频搜索
  if (currentIndex.value === 0) {
    const res = await searchVideoAPI(userId.value, InputVal.value)
    const mergedList = res.data.map(item => ({
      ...item.Video,
      ...item.WSLCNum
    }))
    VideoList.value = mergedList
  }
  // 用户搜索
  else {
    const res = await searchUserAPI(userId.value, InputVal.value)
    console.log(res.data)
    UserList.value = res.data
    // 检查是否有用户头像没有http前缀
    UserList.value.forEach(item => {
      if (!item.userAvatar.includes('http')) {
        item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
      }
    })
  }
}
const isShow = computed(() => InputVal.value !== '')

const handleTabChange = (index) => {
  InputVal.value = ''
  currentIndex.value = index
  VideoList.value = []
  UserList.value = []
}

// 视频播放页
const currentVideoIndex = ref(0)
const showVerticalFeed = ref(false)
const VerticalFeed = defineAsyncComponent(() => import('@/components/common/VerticalFeed.vue'))

// 点击视频播放
const handleVideoClick = (videoId) => {
  currentVideoIndex.value = VideoList.value.findIndex(item => item.videoId === videoId)
  showVerticalFeed.value = true
}

//  清空输入框
const clearInput = () => {
  InputVal.value = ''
  VideoList.value = []
  UserList.value = []
  // 清空输入框焦点
  InputRef.value.focus()
}

// 关注/取消关注用户
const handleFollow = async (followUserId) => {
  const res = await followUserAPI(userId.value, followUserId)
  // 更新UI
  const userItem = UserList.value.find(item => item.userId === followUserId)

  // 根据API返回的结果和当前状态进行状态转换
  if (res.data == '关注成功') {
    // 关注操作成功
    if (userItem.myRelation === 'none') {
      // 无关系 -> 已关注
      userItem.myRelation = 'follow'
    } else if (userItem.myRelation === 'fan') {
      // 对方关注我 -> 相互关注
      userItem.myRelation = 'both'
    }
  } else if (res.data == '取消关注成功') {
    // 取消关注操作成功
    if (userItem.myRelation === 'follow') {
      // 已关注 -> 无关系
      userItem.myRelation = 'none'
    } else if (userItem.myRelation === 'both') {
      // 相互关注 -> 对方关注我
      userItem.myRelation = 'fan'
    }
  }
}

// 显示 好友主页
import { useRouter } from 'vue-router'
const router = useRouter()
const handleFriendClick = (friendUserId) => {
  // 跳转到好友主页
  router.push({
    name: 'friends',
    query: {
      userId: friendUserId
    }
  })
}



</script>
<style lang="scss" scoped>
.search_page {
  background-color: #1a1b20;
  min-height: 100vh;
  display: flex;
  flex-direction: column;

  .flex-grow {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .search_user_video_list {
    padding: 10px 2px;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    align-content: flex-start;


    .item {
      width: 50%;
      height: 245px;
      margin-bottom: 5px;
      background: #1a1b20;
      overflow: hidden;
      display: flex;
      position: relative;

      .avatar {
        flex-shrink: 0;
        width: 100%;
        height: 100%;
      }


      .item_bottom_info {
        position: absolute;
        left: 0;
        bottom: 0;
        padding: 8px;
        color: #e8e8e9;
        font-size: 14px;

        .item_bottom_info_desc {
          font-size: 10px;
          font-weight: bold;
          margin-bottom: 4px;
          // 最多显示三行超出...
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }

        .item_bottom_info_user {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .item_bottom_info_user_userimg {
            display: flex;
            align-items: center;

            img {
              width: 35px;
              height: 35px;
              border-radius: 50%;
              margin-right: 4px;
            }

            .item_bottom_info_user_userimg_name {
              font-size: 10px;
              font-weight: bold;
            }

          }

          .item_bottom_info_user_lick {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 10px;
            font-weight: bold;

            .item_bottom_info_user_lick_item {
              display: flex;
              gap: 2px;
              align-items: center;
            }
          }
        }
      }


    }
  }

  // 默认显示暂无数据快搜索吧~
  .no_data {
    width: 100%;
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    color: #879394;
    margin-top: 20px;
    padding-bottom: 20px;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }



  .fan_list {
    padding: 10px;
    flex: 1;
    overflow-y: auto;

    .fan_item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;


      .avatar {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        margin-right: 10px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .info {
        flex: 1;


        .name {
          font-size: 14px;
          font-weight: bold;
          line-height: 1;
          color: #fff;
        }

        .desc {
          font-size: 14px;
          color: #fff;
          margin-bottom: 5px;
          font-weight: bold;
        }

        .time {
          font-size: 12px;
          font-weight: bold;
          color: #879394;
        }
      }

      .follow {
        width: 60px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        color: #fff;
        padding: 4px 8px;
        border-radius: 2px;
        white-space: nowrap;
        background-color: #f9355f;
        transition: all 0.3s ease-in-out;


        &.active {
          background-color: #393b44;

        }
      }
    }
  }






}

.comment_list_wrap_search {
  padding: 10px 20px;

  .input_wrap {
    width: 100%;
    background: #242630;
    border-radius: 5px;
    height: 44px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;

    .input {
      height: 21px;
      background: #1a1b20;
      -webkit-box-flex: 1;
      -ms-flex: 1;
      flex: 1;
      font-size: 14px;
      color: #e8e8e9;
      padding-left: 10px;
      background: none;
      caret-color: #face15;
    }



    .lf {
      margin-left: 10px;
    }

    .rt {
      margin-right: 10px;
    }
  }
}

// 从左到右过渡出现
.fade-in-right-enter-active,
.fade-in-right-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-in-right-enter-from,
.fade-in-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>